package org.dolphin.action.interceptor;

import java.util.Locale;
import org.dolphin.service.base.CustomAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.I18nInterceptor;

public class LocaleInterceptor extends I18nInterceptor {
  private static final long serialVersionUID = -2983667737877184507L;
  private final static Logger LOG = LoggerFactory.getLogger(LocaleInterceptor.class);

  @Override
  public void destroy() {
    LOG.info(LocaleInterceptor.class.getName() + " is destroyed");
  }

  @Override
  public void init() {
    LOG.info(LocaleInterceptor.class.getName() + " is created");
  }

  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Locale locale = invocation.getInvocationContext().getLocale();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Locale userLocale = null;
    if (authentication instanceof CustomAuthentication) {
      CustomAuthentication customAuthentication = (CustomAuthentication) authentication;
      userLocale = customAuthentication.getLocale();
    }
    if (userLocale != null && !ObjectUtils.nullSafeEquals(locale, userLocale)) {
      saveLocale(invocation, userLocale);
    }
    final String result = invocation.invoke();
    return result;
  }
}
